<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
import { PlanCancel, PlanReceive } from "@/services/requiregoods";
import { orderList, orderVerify } from "@/services/cancellation";

// import {
//   purchaseQuery,
//   PurchaseCancel,
//   purchaseCount,
// } from "@/services/delivery";

// import tabbarView from "../components/tabbar.vue";
const scrollTop = ref(0);
const code = ref("");
const listTabs = ref([
  {
    name: "全部",
    available: "",
  },
  {
    name: "待核销",
    available: "8",
  },
  {
    name: "已核销",
    available: "-11",
  },
  {
    name: "已退款",
    available: "6",
  },
]);
const currentTabs = ref(0);

const changeTabs = (index) => {
  console.log(index);
  form.value.status = index.available ? index.available : "";
  getAppProductQuery(1);
};
const isLoad = ref(false);

onLoad((option) => {
  code.value = option.code ? option.code : "";
  form.value.keywords = option.code ? option.code : "";
  form.value.status = option.status ? option.status : "";
  // if (form.value.deliverStatus === "0") {
  //   currentTabs.value = 1;
  // }
  // if (form.value.deliverStatus == 5) {
  //   currentTabs.value = 2;
  // }
  // if (form.value.deliverStatus == 10) {
  //   currentTabs.value = 3;
  // }
  // if (form.value.deliverStatus == 20) {
  //   currentTabs.value = 4;
  // }
  // getPurchaseCountObj();
});
onShow(() => {
  getAppProductQuery(1);
  // }
});

const getPurchaseCountObj = async () => {
  try {
    let res = await PlanStatus();
    listTabs.value = [];
    listTabs.value.push({
      name: "全部",
      available: 0,
    });

    for (let key in res.data) {
      console.log(key, res.data[key]);

      listTabs.value.push({
        name: res.data[key],
        available: key,
      });
    }
    currentTabs.value = 0;
    getAppProductQuery();
    isLoad.value = true;
  } catch (e) {}
};

const saveFun = () => {
  // console.log("取消");
  // form.value.name = "";
  // loading.value = "";
  // getAppProductQuery(1);
};

onReachBottom(() => {
  console.log("触底了");
  getAppProductQuery();
});

//获取商品
const form = ref({
  page: 1,
  limit: 20,
  createStartTime: "",
  createEndTime: "",

  keywords: "",
});

const productData = ref([]);

const loading = ref("");
const getAppProductQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
    loading.value = "Loading";
  }
  if (index) {
    form.value.page = index;
  }
  if (loading.value == "noMore") {
    return;
  }
  loading.value = "Loading";
  try {
    uni.showLoading({
      title: "加载中",
    });
    let res = await orderList(form.value);
    if (res.code == 200) {
      productData.value = productData.value.concat(res.data.list);
      console.log(productData.value);
      form.value.page = form.value.page + 1;

      if (res.data.list.length < form.value.limit) {
        loading.value = "noMore";
      } else {
        loading.value = "More";
      }
    } else {
    }

    console.log(res);
  } catch (e) {}
};

//编辑商品
const goEdt = (item) => {
  uni.navigateTo({ url: "/pages/cancellation/det/index?id=" + item.order_id });
};
const scanFun = () => {
  console.log("扫码");
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index?type=goods" });
  // #endif
  // #ifdef APP-PLUS
  // 允许从相机和相册扫码
  uni.scanCode({
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      form.value.keywords = res.result;
      getAppProductQuery(1);
    },
  });
  // #endif
};
const searchFun = () => {
  console.log("搜索");
  uni.navigateTo({
    url: "/pages/goods/goods_search/index",
  });
};
const goadd = () => {
  uni.navigateTo({
    url: "/pages/goods/goods_add/index?type=add",
  });
};

const searchlistfun = () => {
  getAppProductQuery(1);
};
const clearlistfun = () => {
  getAppProductQuery(1);
};

const upper = (e) => {
  console.log(e);
};
const lower = (e) => {
  console.log(e);
};
const scroll = (e) => {
  console.log(e);
};
const sandfun = (item) => {
  uni.navigateTo({
    url: "/pages/sends/list/index",
  });
};

const upFun = (item) => {
  uni.navigateTo({
    url: "/pages/require_goods/goods_sel/index?id=" + item.id,
  });
};

const cancelFun = async (item) => {
  uni.showModal({
    title: "提示",
    content: "确定取消该要货计划吗？",
    success: async (res) => {
      if (res.confirm) {
        console.log("用户点击确定");
        const res = await PlanCancel({ id: item.id });
        if (res.code == 200) {
          uni.showToast({
            title: "取消成功",
            icon: "none",
          });
          getAppProductQuery(1);
        }
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};
const selectShow = ref(false);

const selectSearchDate = () => {
  selectShow.value = true;
};

function Time2(e) {
  const date = new Date(e);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

const createStartTimeShow = ref(false);
const createEndTimeShow = ref(false);
const dataOne = ref(Time2(new Date()));
const dataTwo = ref(Time2(new Date()));

const maxCountdata = ref(new Date().getTime());

const createStartTimefun = (e) => {
  dataOne.value = Time2(e.value);
  console.log(e.value, e.value > maxCountdata.value);
  if (e.value > maxCountdata.value) {
    maxCountdata.value = e.value;
    dataTwo.value = Time2(e.value);
  }

  createStartTimeShow.value = false;
};
const createEndTimefun = (e) => {
  dataTwo.value = Time2(e.value);
  // maxCountdata.value = e.value;
  createEndTimeShow.value = false;
};
const qxTime = () => {
  form.value.createStartTime = "";
  form.value.createEndTime = "";
  getAppProductQuery(1);
  selectShow.value = false;
};

const selectdateTime = (e) => {
  form.value.createStartTime = dataOne.value + " 00:00:00";
  form.value.createEndTime = dataTwo.value + " 23:59:59";
  getAppProductQuery(1);
  selectShow.value = false;
};

const selectStatus = (num, list) => {
  let arr = list.filter((item) => {
    return item.available == num;
  });
  return arr[0].name;
};

const showP = ref(false);
const goodsList = ref([]);
const order_id = ref("");
const verifyCode = ref("");
const isTK = ref(false);
const takeFun = (item) => {
  item.orderProduct.forEach((element) => {
    if (!element.total_num) {
      element.total_num = element.product_num;
    }

    if (element.is_refund >= 1) {
      if (element.refund_num <= 0) {
        element.product_num = 0;
        element.num = 0;
      } else {
        element.num = element.refund_num;
        element.product_num = element.refund_num;
      }
    } else {
      element.num = element.product_num;
    }
  });
  goodsList.value = item.orderProduct;
  order_id.value = item.order_id;
  verifyCode.value = item.verify_code;
  isTK.value = false;
  showP.value = true;
  // uni.navigateTo({
  //   url: "/pages/sends/listsends/index",
  // });
  // uni.showModal({
  //   title: "提示",
  //   content: "请检测货物数量是否正确，是否确定收货？",
  //   success: async (res) => {
  //     if (res.confirm) {
  //       console.log("用户点击确定");
  //       const res = await PlanReceive({ id: item.id });
  //       if (res.code == 200) {
  //         uni.showToast({
  //           title: "确认收货成功",
  //           icon: "none",
  //         });
  //         item.status = 9;
  //       }
  //     } else if (res.cancel) {
  //       console.log("用户点击取消");
  //     }
  //   },
  // });
};
const goRecord = async () => {
  if (isTK.value) {
    return;
  }
  isTK.value = true;

  let datas = [],
    isU = false;
  goodsList.value.forEach((item) => {
    if (item.num > 0) {
      datas.push({
        id: item.order_product_id,
        num: item.num,
      });
      isU = true;
    }
  });
  if (!isU) {
    uni.showToast({
      title: "请选择核銷商品",
      icon: "none",
    });
    return;
  }
  console.log("datas", datas);

  try {
    let res = await orderVerify({
      id: order_id.value,
      data: datas,
      verifyCode: verifyCode.value,
    });
    console.log("核销结果", res);

    if (res.code == 200) {
      uni.showToast({
        title: "核销成功",
        icon: "success",
      });
      isTK.value = false;
      showP.value = false;
      getAppProductQuery(1);
      // setTimeout(() => {
      //   uni.navigateTo({
      //     url: "/pages/cancellation/list/index",
      //   });
      //      isTK.value = false;
      // }, 1500);
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
      isTK.value = false;
    }
  } catch (e) {
    isTK.value = false;
    uni.showToast({
      title: e.msg,
      icon: "none",
    });
  }
};
</script>

<template>
  <topNav
    title="线上订单列表"
    @search="searchFun"
    @scan="scanFun"
    rType="save"
    :clickable="false"
  ></topNav>
  <view class="pay-top">
    <view class="pay-search">
      <view class="pay-search-left">
        <up-search
          placeholder="收货人/手机号/订单号"
          v-model="form.keywords"
          @search="searchlistfun"
          @clear="clearlistfun"
          :showAction="false"
          shape="square"
        ></up-search>
      </view>
      <view
        class="pay-search-right"
        :class="selectShow ? 'pay-search-right2' : ''"
        @click="selectSearchDate"
      >
        <text>筛选</text>
        <up-icon
          class="play-right-fill"
          :class="selectShow ? 'rotate' : ''"
          name="play-right-fill"
          :color="selectShow ? '#1679fb' : '#c9cdd4'"
          size="24rpx"
        ></up-icon>
      </view>
    </view>
    <up-tabs
      v-if="listTabs"
      :list="listTabs"
      @change="changeTabs"
      lineWidth="30rpx"
      lineColor="#1679FB"
      :activeStyle="{
        color: '#1679FB',
        fontWeight: '500',
        transform: 'scale(1.05)',
      }"
      :inactiveStyle="{
        color: '#4E5969',
        transform: 'scale(1)',
      }"
      itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;"
    >
    </up-tabs>
  </view>

  <view class="goods_form">
    <view
      class="scr_item"
      v-for="(item, index) in productData"
      :key="index"
      @click="goEdt(item)"
    >
      <view class="item_title">
        <view class="item_title_left">
          <text>{{ item.real_name }}&nbsp; {{ item.user_phone }}</text>
        </view>

        <text
          class="state"
          :class="
            item.status == -1
              ? 'state0'
              : item.verify_time
              ? 'state5'
              : !item.verify_time
              ? 'state10'
              : ''
          "
          >{{
            item.status == -1
              ? "已退款"
              : item.verify_time
              ? "已核销"
              : !item.verify_time
              ? "待核销"
              : ""
          }}</text
        >
      </view>

      <view class="item_content">
        <scroll-view
          class="scroll-view_H"
          scroll-x="true"
          @scroll="scroll"
          scroll-left="0"
        >
          <view
            id="demo1"
            class="scroll-view-item_H"
            v-for="(itemPr, indexPr) in item.orderProduct"
            :key="index"
          >
            <image
              :src="
                itemPr.cart_info.productAttr.image ||
                'https://cloud-erp.yibaitao.cn/0d2f4178-7754-4686-9213-b174f745258b.png'
              "
              mode="scaleToFill"
            />
            <view class="scroll-view-name">{{
              itemPr.cart_info.product.store_name
            }}</view>
            <!-- <view
              class="scroll-view-item_top"
              :class="itemPr.isStandard ? 'bp' : ''"
              >{{ itemPr.isStandard ? "标品" : "非标品" }}
            </view> -->
          </view>
          <!-- <view
            id="demo1"
            class="scroll-view-item_H"
           
          >
            <image
              src="https://cloud-test.yibaitao.com/74429e4c4ad3440e9d7dd8acf29cd5a8.png"
              mode="scaleToFill"
            />
            <view class="scroll-view-name">聚聚聚聚聚12312</view>
          </view> -->
        </scroll-view>

        <view class="item_content-right">
          <view>
            <view class="item_content-right-22"
              >共{{ item.orderProduct.length }}款
            </view>
            <view class="item_content-right-22">{{ item.total_num }}件</view>
          </view>
        </view>
      </view>
      <!-- <view class="item_bt_time"
        >期望送达日期：<text>{{ item.expectDate }}</text>
      </view> -->

      <view
        class="bt_foods"
        v-permission="['shop:mulin:order:verify']"
        v-if="item.status != -1 && !item.verify_time"
      >
        <view
          class="bt_fh bt_qr"
          v-if="item.status != -1 && !item.verify_time"
          @click.stop="takeFun(item)"
          >核销订单</view
        >
      </view>
    </view>
  </view>
  <view class="noData" v-if="productData.length <= 0 && loading == 'noMore'">
    <view class="noData-img">
      <image src="@/static/nodate/datas.png" mode="scaleToFill" />
      <view>暂无商品 </view>
    </view>
  </view>
  <view class="loading-form" v-if="loading && productData.length > 0"
    ><van-loading size="24rpx" v-if="loading == 'Loading'"
      ><text class="loading-text">加载中...</text>
    </van-loading>
    <text class="loading-text" v-if="loading == 'More'">加载更多</text>
    <text class="loading-text" v-if="loading == 'noMore'">~没有数据了~</text>
  </view>

  <!-- <view style="width: 100%; height: 100rpx"></view> -->

  <!-- <view class="goods_bt">
    <view class="goods_bt_to"
      ><up-button
        @click="goadd"
        type="primary"
        icon="plus"
        color="#1679FB"
        text="新增商品"
      ></up-button>
    </view>
  </view> -->

  <up-popup
    :show="selectShow"
    mode="bottom"
    @close="selectShow = false"
    round="10"
    :closeOnClickOverlay="true"
    :safeAreaInsetBottom="true"
    :closeable="true"
  >
    <view class="popup-time">
      <view class="popup-time-title">筛选时间</view>
      <view class="popup-time-item">
        <view
          class="popup-time-item-title"
          @click="createStartTimeShow = true"
          >{{ dataOne }}</view
        >
        <view class="popup-time-item-content">-</view>
        <view class="popup-time-item-title" @click="createEndTimeShow = true">{{
          dataTwo
        }}</view>
      </view>
      <view class="popup-bt-k">
        <up-button @click="qxTime" class="popup-qx" text="取消"></up-button>
        <up-button
          class="popup-bt"
          text="确定"
          @click="selectdateTime"
        ></up-button>
      </view>
    </view>
  </up-popup>
  <up-datetime-picker
    :show="createStartTimeShow"
    v-model="dataOne"
    @cancel="createStartTimeShow = false"
    @confirm="createStartTimefun"
    mode="date"
  ></up-datetime-picker>
  <up-datetime-picker
    :show="createEndTimeShow"
    :minDate="maxCountdata"
    v-model="dataTwo"
    @cancel="createEndTimeShow = false"
    @confirm="createEndTimefun"
    mode="date"
  ></up-datetime-picker>

  <up-popup
    :show="showP"
    :closeOnClickOverlay="true"
    mode="bottom"
    @close="showP = false"
    round="15rpx"
    :closeable="true"
  >
    <view class="sel_p">
      <view class="sel_p-title">订单核销</view>

      <view>
        <scroll-view scroll-y="true" class="scroll-Y">
          <view
            class="scroll-Y-item"
            v-for="(item, index) in goodsList"
            :key="index"
          >
            <view class="content-item">
              <view class="content-item-left">
                <!-- <text class="goods-item-cz"
              >{{ item.dhCode ? "称重" : "计件" }} </text
            > -->
                <image
                  :src="item.cart_info.productAttr.image"
                  mode="scaleToFill"
              /></view>
              <view class="content-item-right">
                <view class="content-item-right-title">
                  <text>{{ item.cart_info.product.store_name }}</text>
                </view>

                <view class="content-item-right-num">
                  <view class="content-item-right-num-gg"
                    ><text>{{ item.cart_info.productAttr.sku }}</text>
                  </view>
                  <view class="content-item-right-num-left"
                    ><text>{{ item.categoryName }}</text>
                  </view>
                  <view class="content-item-right-num-right">
                    <up-number-box
                      v-model="item.num"
                      min="0"
                      :max="item.product_num"
                    ></up-number-box>
                  </view>
                </view>

                <view class="content-item-right-price">
                  <view
                    ><text>¥</text
                    >{{
                      item.cart_info.product.price
                        ? item.cart_info.product.price
                        : "0"
                    }}
                    &nbsp;
                  </view>
                  <view class="refund" v-if="item.is_refund >= 1"
                    >{{
                      item.is_refund == 1
                        ? "退款中"
                        : item.is_refund == 2
                        ? "部分退款"
                        : item.is_refund == 3
                        ? "退款"
                        : ""
                    }}x{{ item.total_num - item.refund_num }}</view
                  >
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="goods_bt_to">
        <van-button class="val-button" type="primary" @click="goRecord"
          >确认核销</van-button
        >
      </view>
    </view>
  </up-popup>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
